package com.vipbbo.security.springboot.controller;

import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;


/**
 * @author bbo(zbw)
 * Description 登录Controller，对/login请求处理，它调用AuthenticationService完成认证并返回登录结果提示信息：
 * @Date 2021/4/22
 */

@RestController
public class LoginController {

    @RequestMapping(value = "/login-success", produces = {"application/json;", "text/html;charset=UTF-8;"})
    public String loginSuccess() {
        // 提示具体用户名称登录成功
        return getUsername()+"login success";
    }

    /*
    测试资源1
     */
    @GetMapping(value = "/r/r1", produces = {"application/json;", "text/html;charset=UTF-8;"})
    @PreAuthorize("hasAnyAuthority('p1')") // 拥有p1权限才可以访问  基于方法的授权
    public String r1() {
        return getUsername()+"访问资源1";
    }

    /*
       测试资源2
     */
    @GetMapping(value = "/r/r2", produces = {"application/json;", "text/html;charset=UTF-8;"})
    @PreAuthorize("hasAnyAuthority('p2')") // 拥有p2权限才可以访问
    public String r2() {
        return getUsername()+"访问资源2";
    }

    // 获取当前用户信息
    private String getUsername() {
        // 当前用户认证通过的身份
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (!authentication.isAuthenticated()) {
            return null;
        }
        Object principal = authentication.getPrincipal();
        String username = null;
        if (principal ==null){
            username = "niming";
        }
        if (principal instanceof org.springframework.security.core.userdetails.UserDetails) {
            UserDetails userDetails = (UserDetails)principal;
            username = userDetails.getUsername();
        } else {
            username = principal.toString();

        }
        return username;
    }
}